package spitter.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import spittr.Spitter;
import spittr.data.SpittleRepository;

/**
 * Created by gongyan on 17/4/5.
 */
@Controller
@RequestMapping("/spittles")
public class SpittleController {


    private SpittleRepository spittleRepository;

    // 注入SpittleRepository
    @Autowired
    public SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String spittles(@RequestParam(value = "max", defaultValue = "30") long max,
                           @RequestParam(value = "count", defaultValue = "3") int count,
                           Model model) {
        model.addAttribute("spittleList", spittleRepository.findSpittles(Long.MAX_VALUE, count));
        return "spittles"; // 返回视图名
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegistrationForm() {
        return "registerForm";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(Spitter spitter, Model model) {

        // 对于基本参数的
        if (spitter.getUserName() == null || spitter.getUserName().length() <= 5) {
            model.addAttribute("message","对不起,userName不符合!");
            return "registerForm";
        }
        spittleRepository.save(spitter);
        return "redirect:/spittles/" + spitter.getUserName();
    }

    @RequestMapping(value = "/{userName}", method = RequestMethod.GET)
    public String showSpitterProfile(@PathVariable String userName, Model model) {
        Spitter spitter = spittleRepository.findByUserName(userName);
        model.addAttribute("spitter", spitter);
        return "profile";
    }

}
